package jt.classic.system.tablequery;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jt.classic.system.ISystem;
import jt.classic.system.context.ISystemContext;
import jt.classic.system.database.SystemDataSource;
import jt.classic.system.user.IUser;
import jt.classic.system.user.UserManager;
import jt.classic.system.utils.AnnexTool;
import jt.classic.system.utils.ResultJsonLoader;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.limp.basework.Column;
import org.limp.basework.Table;
import org.limp.basework.impl.CommonBean4HSQ;
import org.limp.mine.DateTrimmer;
import org.limp.mine.Label;
import org.limp.mine.QueryJack;
import org.limp.mine.QueryJackFactory;
import org.limp.mine.StringTool;
import org.limp.mine.annex.AnnexInfo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 
 * @author mido
 * 
 */
public class JQueryDataTableARGAction extends DispatchAction {
	/**
	 * 查询列表显示项组件
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward modelcmp(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (ISystemContext.invalidSesstion(request)) {
			IUser user = UserManager.createGuestUser();

			ISystemContext.createSessionUser(request, user);
		}

		IUser user = ISystemContext.getSessionUser(request);

		CommonBean4HSQ req = new CommonBean4HSQ(request);

		Map param = req.getResource();

		param.put("sessionUserLogid", user.ilogid());
		param.put("sessionUserId", user.id());
		param.put("sessionUserName", user.iname());
		param.put("sessionGroupId", (user.igroup() != null) ? user.igroup()
				.id() : "");
		param.put("sessionGroupName", (user.igroup() != null) ? user.igroup()
				.iname() : "");
		param.put("sessionGroupNumber", (user.igroup() != null) ? user.igroup()
				.inumber() : "");

		String sessionDate = DateTrimmer.getYMD();
		param.put("sessionYear", sessionDate.substring(0, 4));
		param.put("sessionMonth", sessionDate.substring(0, 6));
		param.put("sessionDay", sessionDate);

		String querykey = StringTool.checkString(param.get("querykey"));

		/* 默认组建类型 */
		String comptype = StringTool.defaultForEmpty((String) param
				.get("comptype"), "defaultFnRender");

		TableQuery tq = null;

		if (querykey.equals("")) {
			ResultJsonLoader.loadErrorJson(request, "没有指定查询key,无法初始化系统对象数据列表");
		} else {
			TableQueryCenter center = TableQueryCenter.getInstance();
			tq = center.getTableQuery(querykey);
		}

		if (tq == null) {
			ResultJsonLoader.loadErrorJson(request, "通用查询设置无效,无法初始化数据列表");
		} else if (tq.iresultItems() == null) {
			ResultJsonLoader.loadErrorJson(request, "无列表显示项定义,无法初始化数据列表");
		} else {

			Table table = (Table) tq.itables().get(0);

			List viewList = tq.iresultItems();

			List viewJsonList = new ArrayList();

			List aoColumnDefsList = new ArrayList();

			if (table.hasPrimaryKey()) {
				try {
					Column column = table.column(table.getPrimaryKey()[0]);

					Map viewMap = new HashMap();

					viewMap.put("mData", column.getName());
					viewMap.put("sTitle", column.getDescription());
					viewMap.put("sWidth", "auto");
					viewMap.put("fnRenderName", comptype);
					viewMap.put("fnRenderColumnName", column.getName());
					viewMap.put("show", "-1");
					viewMap.put("alien", "0");

					viewJsonList.add(viewMap);

					if (tq.ishowchk()) {
						Map viewChkMap = new HashMap();

						viewChkMap.put("mData", "datatable_chk");
						viewChkMap.put("sTitle", "选择");
						viewChkMap.put("sWidth", "auto");
						viewChkMap.put("fnRenderName", comptype);
						viewChkMap.put("fnRenderColumnName", "datatable_chk");
						viewChkMap.put("show", "0");
						viewChkMap.put("alien", "0");

						viewJsonList.add(viewChkMap);
					}

				} catch (Exception ex) {
					ISystem.catchException(ex);
				}
			}

			if ((viewList != null) && !viewList.isEmpty()) {
				if (true) {
					Map viewMap = new HashMap();

					viewMap.put("mData", "PAGINATION_NUMBER");
					viewMap.put("sTitle", "序号");
					viewMap.put("sWidth", "auto");
					viewMap.put("fnRenderName", comptype);
					viewMap.put("fnRenderColumnName", "PAGINATION_NUMBER");
					viewMap.put("show", "0");
					viewMap.put("alien", "0");

					viewJsonList.add(viewMap);
				}

				for (int i = 0; i < viewList.size(); i++) {
					Map item = (Map) viewList.get(i);

					if ("1".equals(item.get("alien"))) {
						Map viewMap = new HashMap();
						viewMap.put("mData", item.get("fieldName"));
						viewMap.put("mLabel", item.get("label"));
						viewMap.put("fnRenderName", comptype);
						viewMap
								.put("fnRenderColumnName", item
										.get("fieldName"));
						viewMap.put("show", item.get("show"));
						viewMap.put("alien", "1");

						viewJsonList.add(viewMap);
					} else {
						Map viewMap = new HashMap();
						viewMap.put("mData", item.get("fieldName"));
						viewMap.put("sTitle", item.get("label"));
						viewMap.put("sWidth", "auto");
						viewMap.put("fnRenderName", comptype);
						viewMap
								.put("fnRenderColumnName", item
										.get("fieldName"));
						viewMap.put("show", item.get("show"));
						viewMap.put("alien", "0");

						viewJsonList.add(viewMap);
					}
				}
			}

			List list = new ArrayList();

			List queryList = tq.iqueryItems();

			if ((queryList != null) && !queryList.isEmpty()) {
				for (int i = 0; i < queryList.size(); i++) {
					Map item = (Map) queryList.get(i);

					String paramValue = (String) item.get("param");

					if (paramValue.startsWith("@")) {
						paramValue = StringTool.checkString(param
								.get(paramValue.substring(1)));
					}

					TableQueryItemJsonBean bean = new TableQueryItemJsonBean();
					bean.setName((String) item.get("label"));
					bean.setColumn(((Column) item.get("column")).getName());
					bean.setColumnName(((Column) item.get("column"))
							.getDescription());
					bean.setItemType(1);
					bean.setMode((String) item.get("mode"));
					bean.setNeed((String) item.get("need"));
					bean.setPointId((String) item.get("pointId"));
					bean.setPointName((String) item.get("pointName"));
					bean.setParam(paramValue);
					bean.setTable(((Column) item.get("column"))
							.associateTable().getName());
					bean.setTableName(((Column) item.get("column"))
							.associateTable().getDescription());
					bean.setType((String) item.get("type"));
					bean.setColumnType(((Column) item.get("column")).getType()
							.toString());
					bean.setTableHandleType("0");

					list.add(bean);
				}
			}

			String jsonArray = JSON.toJSONString(list);

			Map resultMap = new HashMap();
			resultMap.put("name", tq.iname());
			resultMap.put("purview", tq.ipurview());
			resultMap.put("purviewRole", tq.ipurviewRole());
			resultMap.put("showchk", tq.ishowchk());
			resultMap.put("toolbars", tq.itoolbar());
			resultMap.put("columnModel", viewJsonList);
			// resultMap.put("aoColumnModel", aoColumnDefsList);

			ResultJsonLoader.loadSuccessJson(request, resultMap);
		}

		return mapping.findForward("jsonresult");
	}

	/**
	 * 执行数据查询操作
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (ISystemContext.invalidSesstion(request)) {
			IUser user = UserManager.createGuestUser();

			ISystemContext.createSessionUser(request, user);
		}

		IUser user = ISystemContext.getSessionUser(request);

		Connection conn = null;

		CommonBean4HSQ req = new CommonBean4HSQ(request);

		Map param = req.getResource();

		String jsonparam = StringTool.checkString(param.get("jsonparam"));

		JSONObject jsonobj = JSONObject.parseObject(jsonparam);
		Object sEcho = jsonobj.get("sEcho");

		JSONObject returnjobj = new JSONObject();
		returnjobj.put("sEcho", sEcho);

		// String pageNO = StringTool.checkString(param.get("pageNO"));

		String start = StringTool
				.checkString(jsonobj.get("iDisplayStart"), "0");

		String size = StringTool.checkString(jsonobj.get("iDisplayLength"),
				"20");

		String pageNO = String.valueOf((Integer.parseInt(start) / Integer
				.parseInt(size)) + 1);

		String querykey = StringTool.checkString(param.get("querykey"));

		String orderby = StringTool.checkString(param.get("orderby"));

		String orderbykey = StringTool.checkString(param.get("orderbykey"));

		String queryAction = StringTool.checkString(param.get("queryAction"));

		param.put("sessionUserLogid", user.ilogid());
		param.put("sessionUserId", user.id());
		param.put("sessionUserName", user.iname());
		param.put("sessionGroupId", (user.igroup() != null) ? user.igroup()
				.id() : "");
		param.put("sessionGroupName", (user.igroup() != null) ? user.igroup()
				.iname() : "");
		param.put("sessionGroupNumber", (user.igroup() != null) ? user.igroup()
				.inumber() : "");

		String sessionDate = DateTrimmer.getYMD();
		param.put("sessionYear", sessionDate.substring(0, 4));
		param.put("sessionMonth", sessionDate.substring(0, 6));
		param.put("sessionDay", sessionDate);

		TableQuery tq = null;

		if (querykey.equals("")) {
			ResultJsonLoader.loadErrorJson(request, "没有指定查询key,无法初始化系统对象数据列表");
		} else {
			TableQueryCenter center = TableQueryCenter.getInstance();
			tq = center.getTableQuery(querykey);
		}

		if (tq == null) {
			ResultJsonLoader.loadErrorJson(request, "通用查询设置无效,无法初始化数据列表");
		} else if (tq.iresultItems() == null) {
			ResultJsonLoader.loadErrorJson(request, "无列表显示项定义,无法初始化数据列表");
		} else {
			String orderbyTableName = orderbykey.equals("") ? "" : orderbykey
					.substring(0, orderbykey.indexOf("."));

			String orderbyColumnName = orderbykey.equals("") ? "" : orderbykey
					.substring(orderbykey.indexOf(".") + 1);

			String sql = null;

			List tables = tq.itables();

			Table table = (Table) tables.get(0);

			Column primaryKeyColumn = null;

			if (table.hasPrimaryKey()) {
				try {
					primaryKeyColumn = table.column(table.getPrimaryKey()[0]);

				} catch (Exception ex) {
					ISystem.catchException(ex);
				}
			}

			/* 首次加载列表并且列表默认不显示列表数据 */
			if (queryAction.equals("") && !tq.idefaultlist()) {

				sql = "SELECT ";

				if (table.hasPrimaryKey()) {
					try {
						sql += primaryKeyColumn.getName();
					} catch (Exception ex) {
						ISystem.catchException(ex);
					}

					sql += (" FROM " + table.getName() + " WHERE 1 = -1");
				} else {
					
					sql += (((Column)table.commonColumns().get(0)).getName() +  " FROM " + table.getName() + " WHERE 1 = -1");
				}

			} else {
				sql = TableARGTool.getListSQL4Query(user, tq, param);
			}

			request.setAttribute("orderby", orderby);

			request.setAttribute("orderbykey", orderbykey);

			request.setAttribute("query", param);

			String sql1 = "SELECT COUNT(*) FROM (" + sql + ") TAB";

			String sql2 = sql;

			List orderbyList = tq.iorderbyItems();

			/* 动态排序设置 */
			if (!orderbykey.equals("")) {
				sql2 += (" ORDER BY " + orderbyColumnName + " " + orderby);
			} else if ((orderbyList != null) && !orderbyList.isEmpty()) {
				/* 查询定义中存在排序定义 */
				for (int i = 0; i < orderbyList.size(); i++) {
					Map temp = (Map) orderbyList.get(i);

					String columnName = ((Column) temp.get("column")).getName();
					String mode = (String) temp.get("mode");

					if (i == 0) {
						sql2 += (" ORDER BY " + columnName + " " + mode);
					} else {
						sql2 += (", " + columnName + " " + mode);
					}
				}
			}

			String url = ISystemContext.getContextPath()
					+ "/system/tablearg.do?querykey=" + querykey;

			try {
				SystemDataSource ds = SystemDataSource.getInstance();
				conn = ds.getConnection();

				QueryJack plus = QueryJackFactory.getInstance()
						.createQueryJack(false);

				// 设置
				plus.setParameter(QueryJackFactory.PAGINATION_SQL1, sql1);
				plus.setParameter(QueryJackFactory.PAGINATION_SQL2, sql2);
				plus.setParameter(QueryJackFactory.DATABASE_CONNECTION, conn);
				plus.setParameter(QueryJackFactory.PAGINATION_LINKSTRING, url);
				plus.setParameter(QueryJackFactory.PAGINATION_COUNT, size);
				plus.setParameter(QueryJackFactory.PAGINATION_PAGENO, pageNO);
				plus.setParameter(QueryJackFactory.RENDER,
						new JQueryDataTableRender(tq.iresultAlienItems(), tq
								.iresultHiddenItems(), tq.ishowchk(),
								primaryKeyColumn));

				// plus.setParameter(QueryJackFactory.PAGINATION_UPDATEPAGENO,
				// "");
				List resultList = plus.work();

				List resultAnnexItems = tq.iresultAnnexItems();

				/* 显示项存在附件类型并且表存在主键 */
				if ((resultAnnexItems != null) && !resultAnnexItems.isEmpty()
						&& table.hasPrimaryKey()) {
					AnnexTool annexTool = new AnnexTool(conn);

					String keyColumnName = table.getPrimaryKey()[0];

					for (int j = 0; j < resultList.size(); j++) {
						Map info = (Map) resultList.get(j);

						String id = (String) info.get(keyColumnName);

						for (int i = 0; i < resultAnnexItems.size(); i++) {
							Map temp = (Map) resultAnnexItems.get(i);
							Column column = (Column) temp.get("column");

							AnnexInfo[] annexs = null;

							if ("ALLFREE".equals(column.getFormName()
									.toUpperCase())
									|| "ALLRESTRICT".equals(column
											.getFormName().toUpperCase())) {
								annexs = annexTool.getAnnexs(id, table
										.getName());
							} else {
								annexs = annexTool.getAnnexs(id, table
										.getName(), column.getFormName());
							}

							if ((annexs != null) && (annexs.length > 0)) {
								List annexList = new ArrayList();

								for (int kk = 0; kk < annexs.length; kk++) {
									AnnexInfo ai = annexs[kk];
									Map annexInfo = new HashMap();
									annexInfo.put("id", ai.getID());
									annexInfo.put("name", ai.getName());
									annexInfo.put("fieldname", ai
											.getFieldName());
									annexInfo.put("type", ai.getType());
									annexInfo.put("folder", ai.getRepository());
									annexInfo.put("url", ai.getLinkString());
									annexList.add(annexInfo);
								}

								info.put(column.getName(), annexList);
							}
						}
					}
				}

				// returnjobj.put("aaData",jsonDataArray);

				// 显示标签
				Label label = plus.getLabel();

				returnjobj.put("iTotalRecords", label.totaldata());
				returnjobj.put("iTotalDisplayRecords", resultList.size());
				returnjobj.put("aaData", resultList);

				request.setAttribute("result", JSON.toJSONString(returnjobj));
			} catch (Exception ex) {
				request.setAttribute("result", "{success: false}");
				ISystem.catchException(request, this, ex);
			} finally {
				SystemDataSource.closeConnection(conn);
			}
		}

		return mapping.findForward("jsonresult");
	}
}
